using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace MarcoBarzaghi.Diagnostics
{
    class UpdTraceListenerProvider
    {
        IPAddress addressGroup;
        int groupPort;

        UdpClient client;

        public UpdTraceListenerProvider(IPAddress addressGroup, int groupPort)
        {
            IPEndPoint endPoint = new IPEndPoint(addressGroup, groupPort);
            client = UdpHelper.CreateMulticastGroupClient(endPoint);
        }

        public void StartListening()
        {
            BeginReceive();
        }

        public void StopListening()
        {
            try
            {
                client.DropMulticastGroup(addressGroup);
            }
            catch (Exception e)
            {
                Write("[ERR] {0}", e.Message);
            }
        }

        protected virtual void Write(string format, params object[] args)
        {
            Console.Write(format, args);
        }

        private void AsyncReceive(IAsyncResult result)
        {
            try
            {
                IPEndPoint endPoint = null;
                byte[] data = client.EndReceive(result, ref endPoint);
                string message = Encoding.Default.GetString(data);

                Write(message);
            }
            catch (Exception e)
            {
                Write("[ERR] {0}", e.Message);
            }

            BeginReceive();
        }

        private void BeginReceive()
        {
            try
            {
                client.BeginReceive(new AsyncCallback(AsyncReceive), null);
            }
            catch (Exception e)
            {
                Write("[ERR] {0}", e.Message);
            }
        }
    }
}
